package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/searchUser")
public class SearchUserServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();
    private final Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        // 检查管理员权限
        HttpSession session = request.getSession();
        if (session.getAttribute("adminRole") == null || (int)session.getAttribute("adminRole") != 2) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "无权限执行此操作");
            out.write(gson.toJson(result));
            out.flush();
            return;
        }
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取查询参数
            String keyword = request.getParameter("keyword");
            String searchType = request.getParameter("searchType"); // 可以是name, phone, idCard
            
            // 打印所有请求参数，帮助调试
            // System.out.println("SearchUserServlet - 所有请求参数:");
            // Map<String, String[]> paramMap = request.getParameterMap();
            // for (String key : paramMap.keySet()) {
            //     String[] values = paramMap.get(key);
            //     System.out.println(key + ": " + (values.length > 0 ? values[0] : "null"));
            // }
            
            List<User> users = userService.searchUsers(keyword, searchType);
            
            // 处理用户数据，移除敏感信息
            List<Map<String, Object>> userList = new ArrayList<>();
            for (User user : users) {
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("id", user.getId());
                userMap.put("name", user.getName());
                userMap.put("gender", user.getGender());
                userMap.put("age", user.getAge());
                userMap.put("phone", user.getPhone());
                userMap.put("email", user.getEmail());
                userMap.put("address", user.getAddress());
                userMap.put("idCard", user.getIdCard());
                userMap.put("role", user.getRole());
                userMap.put("status", user.getStatus());
                userMap.put("companyId", user.getCompanyId());
                userMap.put("employeeNumber", user.getEmployeeNumber());
                
                // 如果是公司负责人，添加公司信息
                if (user.getRole() == 1) {
                    userMap.put("companyName", user.getCompanyName());
                    userMap.put("companyAddress", user.getCompanyAddress());
                    userMap.put("companyPhone", user.getCompanyPhone());
                    userMap.put("companyCreditCode", user.getCompanyCreditCode());
                }
                
                userList.add(userMap);
            }
            
            result.put("success", true);
            result.put("users", userList);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "搜索用户失败：" + e.getMessage());
        }
        
        // 打印最终返回的JSON
        String jsonResult = gson.toJson(result);
        // System.out.println("SearchUserServlet - 返回JSON: " + jsonResult);
        
        out.write(jsonResult);
        out.flush();
    }
} 